package com.bdqn.controller;

import com.bdqn.pojo.User;
import com.bdqn.service.UserService;
import com.bdqn.util.FileUploadUtil;
import com.bdqn.util.TokenUtil;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@CrossOrigin //允许跨域
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    FileUploadUtil fileUploadUtil;
    @Autowired
    TokenUtil tokenUtil;
    @PostMapping("/checkLogin")
    public String checkLogin(@RequestBody Map<String,String> map){
        String token=null;
        String uname=map.get("userName");
        String pwd=map.get("password");
        User user= userService.getUser(uname,pwd);
        System.out.println(user);
        if(user!=null){
            //登录成功，生成token字符串
            token=tokenUtil.createToken(user);
        }
        return token;
    }
    @GetMapping("/getUser")
    public User getUser(@RequestHeader("Token") String token){
        int uid=tokenUtil.getUid(token);
        User user=userService.getUser(uid);
        return user;
    }
    @GetMapping("/getUsers")
    public PageInfo<User> getUsers(int pageNum,int pageSize,String uname){
        PageInfo<User> pageInfo=userService.selectPage(pageNum,pageSize,uname);
        return pageInfo;
    }
    @PostMapping("/uploadImg")
    public String uploadImg(MultipartFile file){
        String url=null;
        try {
            url=fileUploadUtil.upload(file);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return url;
    }

    @PostMapping("/addUser")
    public int addUser(@RequestBody User user){
        int row=userService.addUser(user);
        return row;
    }

    @GetMapping("/selectById")
    public User selectById(int id){
        User user=userService.getUser(id);
        return user;
    }

    @GetMapping("/addUserRole")
    public int addUserRole(int uid, @RequestParam("rids") List<Integer> rids){
        int row=userService.addUserRole(uid,rids);
        return row;
    }

    @PostMapping("/updateUser")
    public int updateUser(@RequestBody User user){
        int row=userService.updateUser(user);
        return row;
    }

    @GetMapping("/deleteUser")
    public int deleteUser(int id){
        int row=userService.deleteUser(id);
        return row;
    }

    @GetMapping("/updateStatus")
    public int updateStatus(int id,String status){
        System.out.println(status);
        int row=userService.updateStatus(id,status);
        return row;
    }

    @GetMapping("/getAll")
    public List<User> getAll(){
        List<User> list=userService.getAll();
        return list;
    }
}
